package tech.yunland.shop.domain.service;

import com.moyuer.bsf.domain.dao.UserDao;
import com.moyuer.bsf.domain.model.User;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import tech.yunland.shop.domain.dao.UserPrizeDao;
import tech.yunland.shop.domain.model.UserPrize;

import java.util.List;

/**
 * @author: 袁首京<yuanshoujing@gmail.com>
 * 16/7/7
 */
@Service
@CacheConfig(cacheNames = "shopCache")
public class UserPrizeService {

    private static final String UPDATE_HQL = "update UserPrize up set up.state=-1 where up.owner.id=?";

    @Autowired
    private UserPrizeDao userPrizeDao;
    @Autowired
    private UserDao userDao;

    /**
     * 保存员工提成
     *
     * @param userPrize
     */
    @CacheEvict(key = "#userPrize.id")
    public void save(UserPrize userPrize) {
        // 将之前的记录置为失效状态
        // TODO 以后要改为用定时器计算生效时间改状态
        userPrizeDao.bulkUpdate(UPDATE_HQL, userPrize.getOwnerId());

        userPrize.setState(1);
        userPrizeDao.save(userPrize);
    }

    /**
     * 根据主键读取员工提成
     *
     * @param id
     * @return
     */
    @Cacheable(key = "#id")
    public UserPrize get(String id) {
        return userPrizeDao.get(id);
    }

    /**
     * 标记删除
     *
     * @param id
     */
    @CacheEvict(key = "#id")
    public void delete(String id) {
        UserPrize userPrize = get(id);
        if (userPrize == null || userPrize.getState() == -1) {
            return;
        }

        userPrize.setState(-1);
        userPrizeDao.update(userPrize);
    }

    /**
     * @param param
     * @param states
     * @param organIds
     * @return
     */
    private DetachedCriteria genCriteria(String param, List<Integer> states, List<String> organIds) {
        DetachedCriteria criteria = DetachedCriteria.forClass(UserPrize.class);
        criteria.createCriteria("owner", "ow");//创建一个别名
        if (!StringUtils.isBlank(param)) {
            criteria.add(Restrictions.or(
                    Restrictions.like("ow.name", param, MatchMode.ANYWHERE),
                    Restrictions.like("ow.spell", param, MatchMode.ANYWHERE)
            ));
        }
        if (states != null && states.size() > 0) {
            if (states.size() == 1) {
                criteria.add(Restrictions.eq("state", states.get(0)));
                criteria.add(Restrictions.eq("ow.state", states.get(0)));
            } else {
                criteria.add(Restrictions.in("state", states));
                criteria.add(Restrictions.in("ow.state", states));
            }
        }

        if (organIds != null && organIds.size() > 0) {
            if (organIds.size() == 1) {
                criteria.add(Restrictions.eq("organId", organIds.get(0)));
            } else {
                criteria.add(Restrictions.in("organId", organIds));
            }
        }

        return criteria;
    }

    /**
     * 获取结果集数量
     *
     * @param param
     * @param states
     * @param organIds
     * @return
     */
    public int getResultSize(String param, List<Integer> states, List<String> organIds) {
        DetachedCriteria criteria = genCriteria(param, states, organIds);
        return userPrizeDao.findByCriteria(criteria).size();
    }

    /**
     * 获取结果集
     *
     * @param param
     * @param states
     * @param organIds
     * @param startIndex
     * @param length
     * @return
     */
    public List<UserPrize> getResultList(String param, List<Integer> states, List<String> organIds,
                                         Integer startIndex, Integer length) {
        DetachedCriteria criteria = genCriteria(param, states, organIds);
        criteria.addOrder(Order.desc("createTime"));
        return userPrizeDao.findByCriteria(criteria, startIndex, length);
    }

    public List<User> getUser(List<String> organIds) {
        String organId = StringUtils.join(organIds,"','");
        String hql =
                "SELECT DISTINCT u\n" +
                        "FROM\n" +
                        "  User u\n" +
                        "  , UserOrgans uo\n" +
                        "WHERE\n" +
                        "  uo.user.id = u.id\n" +
                        "  AND u.state = 1\n" +
                        "  AND u.kindCode = '10'\n" +
                        "  AND uo.organ.id in ('" + organId + "')\n" +
                        "  AND u.id\n" +
                        "      NOT IN (\n" +
                        "        SELECT up.owner.id\n" +
                        "        FROM UserPrize up\n" +
                        "          , User u\n" +
                        "        WHERE up.organId in ('" + organId + "')\n" +
                        "              AND up.state = 1\n" +
                        "              AND u.state = 1\n" +
                        "              AND up.owner.id = u.id\n" +
                        "      )";
        return userDao.find(hql);
    }
}
